#include "../server.hpp"

class EchoServer
{
private:
    TcpServer _server;
    void OnConnected(const PtrConnection &conn)
    {
        DBG_LOG("NEW CONNECTION: %p", conn.get());
    }
    void OnClosed(const PtrConnection &conn)
    {
        DBG_LOG("CLOSE CONNECTION: %p", conn.get());
    }

    void OnMessage(const PtrConnection &conn, Buffer *buf)
    {
        DBG_LOG("%s", buf->ReadPosition());

        buf->MoveReadOffset(buf->ReadableSize());

        std::string str = "我收到了你发送的消息";
        conn->Send(str.c_str(), str.size());
        conn->Shutdown(); // 通信一次直接关闭连接
    }

public:
    EchoServer(int port) : _server(port)
    {
        _server.SetThreadCount(2);
        // _server.EnableInactiveRelease(10);
        _server.SetClosedCallBack(std::bind(&EchoServer::OnClosed, this, std::placeholders::_1));
        _server.SetConnectedCallBack(std::bind(&EchoServer::OnConnected, this, std::placeholders::_1));
        _server.SetMessageCallBack(std::bind(&EchoServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
        _server.Start();
    }

    void Start()
    {
        _server.Start();
    }
};